/*
 * $Id: JsonObjectsReaderContainer.java 136 2009-07-16 07:53:43Z donbeave $
 */

package labour.concept.client.data.json;

import java.util.ArrayList;
import java.util.List;

import labour.concept.client.data.BaseObjectsLoadResult;
import labour.concept.client.data.ObjectModel;
import labour.concept.client.data.ObjectModelType;
import labour.concept.client.data.ObjectTextModel;
import labour.concept.client.data.ObjectTextModelType;
import labour.concept.client.data.ObjectsLoadResult;

import com.extjs.gxt.ui.client.data.DataReader;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;

public class JsonObjectsReaderContainer implements DataReader<ObjectsLoadResult<ObjectModel>> {

  protected JsonObjectsReader<ObjectModel> objectsReader;
  protected JsonObjectsTextsReader<ObjectTextModel> textsReader;
//  protected JsonBlocksReader blocksReader;

  public ObjectsLoadResult<ObjectModel> read(Object loadConfig, Object data) {
//    blocksReader = new JsonBlocksReader(new BlockModelType());
    List<ObjectModel> models = getObjectsReader().read(loadConfig, data);

    List<ObjectTextModel> texts = new ArrayList<ObjectTextModel>();

    JSONObject jsonRoot = null;

    if (data instanceof JavaScriptObject) {
      jsonRoot = new JSONObject((JavaScriptObject) data);
    } else {
      jsonRoot = (JSONObject) JSONParser.parse((String) data);
    }

    JSONArray root = (JSONArray) jsonRoot.get(new ObjectModelType().getRoot());

    for (int i = 0; i < root.size(); i++){
      JavaScriptObject jsObject = root.get(i).isObject().getJavaScriptObject();

      List<ObjectTextModel> ot = getTextsReader().read(loadConfig, jsObject);
      texts.addAll(ot);
    }

    return newLoadResult(loadConfig, models, texts);
  }

  public JsonObjectsReader<ObjectModel> getObjectsReader() {
    if (objectsReader == null) {
      objectsReader = new JsonObjectsReader<ObjectModel>(new ObjectModelType());
    }
    return objectsReader;
  }

  @SuppressWarnings("unchecked")
  public void setObjectsReader(JsonObjectsReader<?> reader) {
    objectsReader = (JsonObjectsReader<ObjectModel>) reader;
  }

  public JsonObjectsTextsReader<ObjectTextModel> getTextsReader() {
    if (textsReader == null) {
      textsReader = new JsonObjectsTextsReader<ObjectTextModel>(new ObjectTextModelType());
    }
    return textsReader;
  }

  public void setTextsReader(JsonObjectsTextsReader<ObjectTextModel> reader) {
    textsReader = reader;
  }

  protected ObjectsLoadResult<ObjectModel> newLoadResult(Object loadConfig,
      List<ObjectModel> models, List<ObjectTextModel> texts) {
    return new BaseObjectsLoadResult<ObjectModel>(models, texts);
  }

}
